package xrc.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple2;
import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple3;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import xrc.contract.MaskVoteContract;
import xrc.domain.*;
import xrc.mapper.UserMapper;
import xrc.service.UserService;
import xrc.domain.MaskVote;


import java.sql.*;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    //调用mapper层方法，将user传递下去
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MaskVoteImpl contract;
    ECGroup ecgroup = new ECGroup();
    ECPoint g = new ECPoint(ecgroup.x1, ecgroup.y1);
    ECPoint h = ecgroup.randompoint();
    MaskVote maskVote = new MaskVote();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    int n = 3; //总人数
    int t = 1; //门限值


    /*定义MD5算法加密*/
    private String getMD5Pwd(String pwd, String salt) {

        //进行三次加密
        for (int i = 0; i < 3; i++) {
            //MD5加密算法方法调用
            pwd = DigestUtils.md5DigestAsHex((salt + pwd + salt).getBytes()).toUpperCase();
        }

        //返回加密后的pwd
        return pwd;

    }

    //注册功能
    @Override
    public List<Object> register(JSONObject user) throws SQLException, ClassNotFoundException {

        String name = user.getString("username");   //获取前端传递的姓名以及密码
        String password = user.getString("password");

        System.out.println(user);
        User byName = userMapper.findByUserName(name);

        JSONObject result = new JSONObject();   //创建返回给前端状态
        List<Object> resultList = new ArrayList<>();    //生成结果状态列表

        if (byName != null) {
            //throw new NameDuplicatedException("用户名被占用");

            result.put("result", "注册失败");
            result.put("code", "用户名被占用");
            result.put("key", "");
            resultList.add(result);

        } else {

            String salt = UUID.randomUUID().toString().toUpperCase();
            System.out.println("salt:" + salt);
            String md5Pwd = getMD5Pwd(password, salt);

            Connection connection = contract.connection();
            String sql = "insert into test (name,pwd,salt) values('" + name + "','" + md5Pwd + "','" + salt + "')";
            //System.out.println(sql);
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            int j = preparedStatement.executeUpdate();


            //用户注册时创建密钥
            //调用maskvote中的keygen方法
            BigInteger[][] secret = maskVote.keygen(t, ecgroup);
            System.out.println("ecgroup = " + ecgroup);
            List<String> secretList = new ArrayList<>();   //生成密钥列表

            for (int i = 0; i < t + 1; i++) {
                System.out.println(secret[0][i]);
                System.out.println(secret[1][i]);

                secretList.add(String.valueOf(secret[0][i]));
                secretList.add(String.valueOf(secret[1][i]));
            }

            if (j > 0) {
                result.put("result", "注册成功");
                result.put("code", "");
                result.put("key", secretList);
            } else {
                result.put("result", "注册失败");
                result.put("code", "出现未知错误");
                result.put("key", "");
            }

            resultList.add(result);
            connection.close();
        }
        System.out.println(resultList);

        return resultList;
    }

    //登陆功能进行判断
    @Override
    public List<Object> login(JSONObject user) {
        System.out.println("denglu");

        //根据用户名称来查询用户数据是否存在
        String name = user.getString("username");
        String pwd = user.getString("password");
        System.out.println(user);

        User byName = userMapper.findByUserName(name);
        JSONObject result = new JSONObject();
        List<Object> resultList = new ArrayList<>();

        if (byName == null) {
            //throw new UserNotFoundException("用户数据不存在");
            result.put("result", "登录失败");
            result.put("code", "用户不存在");

        } else {
            String oldPwd = byName.getPwd();

            //检测密码是否匹配
            String salt = byName.getSalt();    //先获取盐值
            String newPwd = getMD5Pwd(pwd, salt);   //将密码按照md5算法进行加密

            System.out.println(newPwd);
            System.out.println(oldPwd);

            //密码进行比较
            if (!oldPwd.equals(newPwd)) {

//            throw new PwdNotMatchException("用户密码错误");
                result.put("result", "登录失败");
                result.put("code", "用户密码错误");
            } else {

                result.put("result", "登录成功");
                result.put("code", "");
            }
        }
        resultList.add(result);
        return resultList;


    }

    //修改用户密码
    @Override
    public List<Object> modify(JSONObject user) {

        //根据用户名称来查询用户数据是否存在
        String name = user.getString("username");
        String newPwd = user.getString("password");
        System.out.println("name = " + name);
        System.out.println("password = " + newPwd);

        User byName = userMapper.findByUserName(name);
        JSONObject result = new JSONObject();
        List<Object> resultList = new ArrayList<>();

        if (byName == null) {

            result.put("result", "登录失败");
            result.put("code", "用户不存在");

        } else {

            String salt = byName.getSalt();
            String md5Pwd = getMD5Pwd(newPwd, salt);
            Integer updatePwd = userMapper.updatePwd(md5Pwd, name);
            if (updatePwd == 0) {
                result.put("result", "修改失败");
                result.put("code", "用户密码修改失败");
            } else {
                result.put("result", "修改成功");
                result.put("code", "");
            }

        }
        resultList.add(result);
        return resultList;
    }

    //获取用户需要进行的投票事项的列表
    @Override
    public List<Object> getWaitForVoteList(JSONObject user) throws Exception {

        String name = user.getString("username");  //获取名字
        System.out.println(name);
        User user1 = userMapper.findId(name);
        String id = String.valueOf(user1.getId());

        Connection connection = contract.connection();
        String sql = "SELECT * FROM EVENT";   //判断当前用户是否包含在投票事项的参与者列表中
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(date); //获取现在时间


        List<Object> resultList = new ArrayList<>();

        while (resultSet.next()) {

            JSONObject result = new JSONObject();

            String sqlName = resultSet.getString("voterList");
            System.out.println(sqlName);
            String substring = sqlName.substring(1, sqlName.length() - 1);
            System.out.println(substring);
            String[] strings = substring.split(", ");

            for (int i = 0; i < strings.length; i++) {

                System.out.println(strings[i]);
                if (name.equals(strings[i])) {

                    String voteId = resultSet.getString("voteId");
                    String timePrevoteStart = resultSet.getString("timePrevoteStart");
                    Date preVote = sdf.parse(timePrevoteStart);
                    String timeVerifyStart = resultSet.getString("timeVerifyStart");
                    Date verify = sdf.parse(timeVerifyStart);
                    Date currentTime = sdf.parse(format);
                    String timeVoteStart = resultSet.getString("timeVoteStart");
                    Date vote = sdf.parse(timeVoteStart);
                    String timeSumStart = resultSet.getString("timeSumStart");
                    Date sumStart = sdf.parse(timeSumStart);
                    String timeSumEnd = resultSet.getString("timeSumEnd");
                    Date sumEnd = sdf.parse(timeSumEnd);

                    if (currentTime.before(preVote)) {
                        result.put("state", "未开始");
                    } else if (currentTime.after(preVote) && currentTime.before(verify)) {
                        result.put("state", "预投票");
                    } else if (currentTime.after(verify) && currentTime.before(vote)) {
                        result.put("state", "验证");
                    } else if (currentTime.after(vote) && currentTime.before(sumStart)) {
                        result.put("state", "投票");
                    } else if (currentTime.after(sumStart) && currentTime.before(sumEnd)) {
                        result.put("state", "计票");
                    } else if (currentTime.after(sumEnd)) {
                        result.put("state", "已结束");
                    }

                    result.put("voteid", resultSet.getString("voteId"));
                    result.put("voteitem", resultSet.getString("voteItem"));
                    result.put("time_prevote_start", timePrevoteStart);
                    result.put("time_verify_start", timeVerifyStart);
                    result.put("time_vote_start", timeVoteStart);
                    result.put("time_sum_start", timeSumStart);
                    result.put("time_sum_end", timeSumEnd);

                    MaskVoteContract client = contract.Client();
                    //需要从智能合约中读取状态
                    TransactionReceipt publish = contract.publish(id, voteId);
                    Tuple2<String, String> publishInput = client.getPublishInput(publish);
                    System.out.println("publishInput = " + publishInput);
                    if (publishInput != null) {
                        result.put("is_prevote", "false");
                        result.put("is_verify", "false");
                        result.put("is_vote", "false");
                        result.put("is_precount", "false");
                    }

                    resultList.add(result);

                }

            }

        }
        connection.close();
        return resultList;

    }

    //用户发起一项投票
    @Override
    public List<Object> publish(JSONObject event) throws Exception {

        String username = event.getString("username");
        String voteItem = event.getString("voteitem");
        String voterList = event.getString("voterlist");

        String timePreVoteStart = event.getString("time_prevote_start");
        System.out.println("time_prevote_start = " + timePreVoteStart);
        String timeVerifyStart = event.getString("time_verify_start");
        System.out.println("time_verify_start = " + timeVerifyStart);
        String timeVoteStart = event.getString("time_vote_start");
        System.out.println("time_vote_start = " + timeVoteStart);
        String timeSumStart = event.getString("time_sum_start");
        System.out.println("time_sum_start = " + timeSumStart);
        String timeSumEnd = event.getString("time_sum_end");
        System.out.println("time_sum_end = " + timeSumEnd);

        JSONObject result = new JSONObject();   //创建返回给前端状态
        List<Object> resultList = new ArrayList<>();    //生成结果状态列表

        String sql1 = "insert into event(username,voteItem,voterList,timePrevoteStart,timeVerifyStart,timeVoteStart,timeSumStart,timeSumEnd)" +
                "values ('" + username + "','" + voteItem + "','" + voterList + "','" + timePreVoteStart + "','" + timeVerifyStart + "','" + timeVoteStart +
                "','" + timeSumStart + "','" + timeSumEnd + "')";

        Connection connection = contract.connection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql1);
        int j = preparedStatement.executeUpdate();

        if (j != 0) {
            result.put("result", "发起投票成功");
            result.put("code", "事项进数据库");
        } else {
            result.put("result", "发起投票失败");
            result.put("code", "事项没进数据库");
        }
        resultList.add(result);

        /*String voteId = userMapper.findSqlId(voteItem);  //获取投票事项id
        System.out.println("获取投票事项id = " + voteId);
        User user = userMapper.findId(username);
        System.out.println("user = " + user);
        String loginId = String.valueOf(user.getId());
        //String loginId = String.valueOf(userMapper.findId(username));  //获取发起投票用户id
        System.out.println("获取发起投票用户id = " + loginId);
        String[] strings = voterList.split(", ");  //获取所有参与者
        int[] idList = new int[strings.length];

        //调用智能合约publish方法将默认修改为false

        Date date = new Date();

        String format = sdf.format(date); //获取现在时间
        System.out.println("获取现在时间String = " + format);

        Date currentTime = sdf.parse(format);
        System.out.println("获取现在时间Date = " + currentTime);
        Date vote = sdf.parse(timeVoteStart);
        Date sumStart = sdf.parse(timeSumStart);
        Date sumEnd = sdf.parse(timeSumEnd);

        if (currentTime.after(vote)) {

            ECPoint[] A0List = new ECPoint[strings.length];   //从智能合约里读取的第i个参与者的A值数组的第一个值
            for (int t = 0; t < strings.length; t++) {
                User voter = userMapper.findId(strings[t]);//获取每个参与者id
                Integer voterIdInt = voter.getId();
                String voterIdString = String.valueOf(voterIdInt);

                idList[t] = voterIdInt;
                ECPoint ecPoint = contract.getA(voterIdString);
                A0List[t] = ecPoint;

            }
            ECPoint Y = maskVote.Y(A0List, ecgroup);
            List<String> YList = new ArrayList<>();
            YList.add(Y.toString());
            for (String s : YList) {
                System.out.println("YList = " + s);
            }

            //将YList上传至智能合约 联合公钥
            TransactionReceipt transactionReceipt = contract.addY(voteId, YList);
            MaskVoteContract client = contract.Client();
            client.getAddYInput(transactionReceipt);

        } else if (currentTime.after(sumStart)) {

            ECPoint en_vote_list[][] = new ECPoint[strings.length][2];
            //调用密码算法的mul_en_vote()接口
            for (int i = 0; i < strings.length; i++) {
                User voter = userMapper.findId(strings[t]);//获取每个参与者id
                Integer voterIdInt = voter.getId();
                String voterIdString = String.valueOf(voterIdInt);
                idList[i] = voterIdInt;
                List SecVote = contract.getSecVote(voterIdString, voteId);
                for (int m = 0; m < SecVote.size(); m++) {

                    System.out.println("SecVote.get(j) = " + SecVote.get(m).toString());
                    String SecVoteString = SecVote.get(m).toString();
                    String[] str = SecVoteString.split(",");
                    BigInteger o1 = new BigInteger(str[0], 16);
                    BigInteger o2 = new BigInteger(str[1], 16);
                    ECPoint ecPoint = new ECPoint(o1, o2);
                    System.out.println("ecPoint = " + ecPoint);
                    en_vote_list[i][m % 2] = ecPoint;
                }

                System.out.println("en_vote_list[0][0] = " + en_vote_list[0][0]);
                System.out.println("en_vote_list[0][1] = " + en_vote_list[0][1]);
                System.out.println(en_vote_list[1][0]);
                System.out.println(en_vote_list[1][1]);
            }

            ECPoint[] mixedVoteList = maskVote.mul_en_vote(en_vote_list, ecgroup);
            for (ECPoint ecPoint : mixedVoteList) {
                System.out.println("ecPoint = " + ecPoint);
            }
            List<String> mixedVote = new ArrayList<>();

            for (int i = 0; i < mixedVoteList.length; i++) {
                mixedVote.add(mixedVoteList[i].toString());
            }
            for (String s : mixedVote) {
                System.out.println("mixedVote = " + s);
            }

            //将相乘结果E存进智能合约
            contract.addMixedVote(voteId, mixedVote);

        } else if (currentTime.after(sumEnd)) {

            ECPoint E0 = contract.getE0(voteId);
            System.out.println("第一项相乘结果为 = " + E0);
            ECPoint[] en_g_R_list = new ECPoint[strings.length];
            for (int i = 0; i < strings.length; i++) {
                User user1 = userMapper.findId(strings[i]);
                String id1 = String.valueOf(user1.getId());
                ECPoint GRi = contract.getg_R(id1, voteId);

                en_g_R_list[i] = GRi;
            }

            for (ECPoint ecPoint : en_g_R_list) {
                System.out.println("ecPoint = " + ecPoint);
            }

            //计算总票数并存放进数据库
            int sum = maskVote.sum(ecgroup, en_g_R_list, h, E0);
            userMapper.updateSum(sum, voteItem);
            System.out.println("sum = " + sum);
        }*/
        connection.close();

        return resultList;


    }

    //获取用户发起的投票事项的列表
    @Override
    public List<Object> getPublishedVoteList(JSONObject event) throws ClassNotFoundException, SQLException, ParseException {

        String name = event.getString("username");    //调取数据库事项表中的用户名 并进行比较

        Connection connection = contract.connection();
        String sql = "SELECT * FROM EVENT";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        Date date = new Date();
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date); //获取现在时间
        Date currentTime = sdf.parse(format);
        List<Object> resultList = new ArrayList<>();


        while (resultSet.next()) {
            JSONObject result = new JSONObject();
            String username = resultSet.getString("username");
            if (name.equals(username)) {

                String voteId = resultSet.getString("voteId");
                String voteItem = resultSet.getString("voteItem");
                String timePrevoteStart = resultSet.getString("timePrevoteStart");
                String voter = resultSet.getString("voterList");
                String[] voterList = voter.split(", ");
                Date preVote = sdf.parse(timePrevoteStart);
                String timeVerifyStart = resultSet.getString("timeVerifyStart");
                Date verify = sdf.parse(timeVerifyStart);

                String timeVoteStart = resultSet.getString("timeVoteStart");
                Date vote = sdf.parse(timeVoteStart);
                String timeSumStart = resultSet.getString("timeSumStart");
                Date sumStart = sdf.parse(timeSumStart);
                String timeSumEnd = resultSet.getString("timeSumEnd");
                Date sumEnd = sdf.parse(timeSumEnd);
                String sum = resultSet.getString("sum");
                result.put("voteid", voteId);
                result.put("voteItem", voteItem);
                result.put("time_prevote_start", timePrevoteStart);
                result.put("time_verify_start", timeVerifyStart);
                result.put("time_vote_start", timeVoteStart);
                result.put("time_sum_start", timeSumStart);
                result.put("time_sum_end", timeSumEnd);

                if (currentTime.before(preVote)) {
                    result.put("state", "未开始");
                } else if (currentTime.after(preVote) && currentTime.before(verify)) {
                    result.put("state", "预投票");
                } else if (currentTime.after(verify) && currentTime.before(vote)) {
                    result.put("state", "验证");
                } else if (currentTime.after(vote) && currentTime.before(sumStart)) {
                    result.put("state", "投票");
                } else if (currentTime.after(sumStart) && currentTime.before(sumEnd)) {
                    result.put("state", "计票");
                } else if (currentTime.after(sumEnd)) {
                    result.put("state", "已结束");
                }
                result.put("voterList", voterList.length);
                result.put("result", sum);
                resultList.add(result);

            }

        }
        connection.close();
        System.out.println(resultList);
        return resultList;

    }

    //预投票：
    //用户提交秘钥，计算该用户的A、C值及该用户对其他参与者的秘密值
    @Override
    public List<Object> preVote(JSONObject user) throws Exception {

        String name = user.getString("username");
        User user2 = userMapper.findId(name);
        String id1 = String.valueOf(user2.getId());

        System.out.println("id1 = " + id1);
        String key = user.getString("key");
        String voteId = user.getString("voteid");
        MaskVoteContract client = contract.Client();

        JSONObject result = new JSONObject();
        List<Object> resultList = new ArrayList<>();

        Connection connection = contract.connection();
        String sql1 = "select * from event";
        PreparedStatement preparedStatement = connection.prepareStatement(sql1);
        ResultSet resultSet = preparedStatement.executeQuery();

        BigInteger[][] keyInt = new BigInteger[2][t + 1];
        String[] keyString = key.split(","); //string-> BigInteger
        for (int i = 0; i < (t + 1); i++) {
            keyInt[0][i] = new BigInteger(keyString[i]);
            keyInt[1][i] = new BigInteger(keyString[i + t]);
        }

        ECPoint[] A = maskVote.A(t, keyInt, ecgroup);  //根据本用户key算出A值
        System.out.println("ecgroup = " + ecgroup);
        for (ECPoint ecPoint : A) {
            System.out.println("本用户A值ecPoint = " + ecPoint);
        }
        List<String> AList = new ArrayList<>();
        String[] str1 = new String[t + 1];

        for (int i = 0; i < A.length; i++) {

            //ECPoint -> string ->BigInteger
            str1[i] = String.valueOf(A[i]);
            AList.add(str1[i]);
        }

        TransactionReceipt addA = contract.addA(id1, AList);//将当前用户的A值上传至智能合约
        System.out.println("addA = " + addA);
        Tuple2<String, List<String>> addAInput = client.getAddAInput(addA);

        ECPoint[] C = maskVote.C(t, keyInt, ecgroup, h);  //根据本用户key算出C值
        System.out.println("ecgroup = " + ecgroup);
        System.out.println("h = " + h);
        for (ECPoint ecPoint : C) {
            System.out.println("本用户C值 = " + ecPoint);
        }
        List<String> CList = new ArrayList<>();
        String[] str2 = new String[t + 1];

        for (int i = 0; i < C.length; i++) {
            //ECPoint -> string ->BigInteger
            str2[i] = String.valueOf(C[i]);
            CList.add(str2[i]);
        }

        TransactionReceipt addC = contract.addC(id1, CList);
        System.out.println("addC = " + addC);
        Tuple2<String, List<String>> addCInput = client.getAddCInput(addC);

        while (resultSet.next()) {

            String sqlId = resultSet.getString("voteId");

            if (voteId.equals(sqlId)) {  //前端voteid与数据库中voteId相同时

                String sqlName = resultSet.getString("voterList");
                String substring = sqlName.substring(1, sqlName.length() - 1);
                System.out.println("substring = " + substring);
                String[] voterList = substring.split(", "); //获取参与者
                for (String s : voterList) {
                    System.out.println("voterList = " + s);
                }

                int idList[] = new int[voterList.length];
                System.out.println("sqlId = " + sqlId);
                for (int i = 0; i < voterList.length; i++) {  //遍历每个参与者
                    System.out.println("voterList[i] = " + voterList[i]);
                    User user1 = userMapper.findId(voterList[i]);//获取参与者id
                    System.out.println("user1 = " + user1);
                    Integer id = user1.getId();
                    System.out.println("id = " + id);
                    System.out.println(id);
                    idList[i] = id;
                }
                for (int i : idList) {
                    System.out.println("参与者用户id为 = " + i);
                }

                //计算每个参与者的秘密值s
                BigInteger S[][] = new BigInteger[voterList.length][2];

                for (int i = 0; i < voterList.length; i++) {
                    int j = idList[i];
//                    BigInteger -> String -> List
                    S[i][0] = maskVote.s(j, t, keyInt)[0];
                    S[i][1] = maskVote.s(j, t, keyInt)[1];
                    System.out.println("计算的秘密值[0] = " + maskVote.s(j, t, keyInt)[0]);
                    System.out.println("计算的秘密值[1] = " + maskVote.s(j, t, keyInt)[1]);
                    System.out.println("当前用户id为 = " + j);


                   /* String[] str = new String[2 * voterList.length];
                    for (int t = 0; t < str.length; t++) {
                        str[t] = String.valueOf(S[t]);
                        System.out.println("str[i1] = " + str[t]);
                        SList.add(str[t]);
                    }*/
                    List<String> SList = new ArrayList<>();
                    SList.add(String.valueOf(S[i][0]));
                    SList.add(String.valueOf(S[i][1]));
                    for (String s : SList) {
                        System.out.println("所有的秘密值为 = " + s);
                    }

                    TransactionReceipt addF = contract.addF(id1, String.valueOf(j), SList);//将每个用户的秘密值添加至智能合约
                    System.out.println();
                    System.out.println("addF = " + addF);

                    Tuple3<String, String, List<String>> addFInput = client.getAddFInput(addF);
                    if (addFInput != null && addAInput != null && addCInput != null) {
                        result.put("result", "预投票成功");
                        result.put("code", "200");

                    } else {
                        result.put("预投票失败", "预投票失败");
                        result.put("code", "failed to preVote");

                    }
                }

            }
        }

        resultList.add(result);
        System.out.println(resultList);
        return resultList;


    }

    //对A，C以及秘密值进行验证
    @Override
    public List<Object> verify(JSONObject user) throws Exception {

        String name = user.getString("username");
        String voteId = user.getString("voteid");
        System.out.println(name + voteId);

        User user1 = userMapper.findId(name);
        Integer loginIdInt = user1.getId();
        System.out.println("当前登录id为 = " + loginIdInt);
        String loginIdString = String.valueOf(loginIdInt);   //当前登录用户id

        List<Object> resultList = new ArrayList<>();

        Map<String, Boolean> verify_A = new HashMap<>();
        Map<String, Boolean> verify_S = new HashMap<>();

        Connection connection = contract.connection();
        String sql = "SELECT * FROM EVENT";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        boolean verifyS = false;
        boolean verifyA = false;
        JSONObject result = new JSONObject();
        while (resultSet.next()) {


            String sqlVoteId = resultSet.getString("voteId");
            if (sqlVoteId.equals(voteId)) {

                String sqlName = resultSet.getString("voterList");
                String substring = sqlName.substring(1, sqlName.length() - 1);
                System.out.println("substring = " + substring);
                String[] voterList = substring.split(", ");  //读取该投票事项id voteid对应的所有参与者voterList的用户名
                System.out.println("voterList = " + voterList[0]);

                for (int i = 0; i < voterList.length; i++) {
                    System.out.println(voterList[i]);
                    User user3 = userMapper.findId(voterList[i]);
                    Integer verifyIdInt = user3.getId();
                    String verifyIdString = String.valueOf(user3.getId());  //参与者用户id
                    System.out.println(verifyIdString);


                    if (loginIdInt != verifyIdInt){

                        //验证秘密值
                        System.out.println("loginIdString = " + loginIdString);
                        System.out.println("verifyId = " + verifyIdString);
                        BigInteger[] s = contract.s(loginIdString, verifyIdString);
                        ECPoint[] CList = contract.verifyS(verifyIdString);
                        verifyS = maskVote.verifi_s(loginIdInt, ecgroup, s, h, t, CList);
                        System.out.println("ecgroup = " + ecgroup);
                        System.out.println("verifyS = " + verifyS);
                        verify_S.put(voteId, verifyS);


                        //验证A值
                        BigInteger s_ji0 = contract.s_ji0(loginIdString, verifyIdString);
                        ECPoint[] AList = contract.verifyA(verifyIdString);

                        verifyA = maskVote.verifi_A(verifyIdInt, ecgroup, s_ji0, t, AList);
                        System.out.println("ecgroup = " + ecgroup);
                        System.out.println("verifyA = " + verifyA);
                        verify_A.put(voteId, verifyA);
                        //调用智能合约中的addVerifyFlag方法，将结果设置为true
                        contract.addVerifyFlag(loginIdString, verifyIdString);
                    }
                }

            }

        }
        System.out.println("verify_A = " + verify_A);
        System.out.println("verify_S = " + verify_S);
        if (verifyS == true && verifyA == true) {
            result.put("result", "验证成功");
            result.put("code", "200");
        } else {
            result.put("result", "验证失败");
            result.put("code", "500");
        }
        resultList.add(result);
        System.out.println(resultList);
        return resultList;

    }

    //获取系统中所有用户
    @Override
    public List<Object> allUser(JSONObject user) throws ClassNotFoundException, SQLException {

        List<Object> resultList = new ArrayList<>();

        Connection connection = contract.connection();
        String sql = "select name from test";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {

            JSONObject result = new JSONObject();
            String username = resultSet.getString("name");
            System.out.println("获得的username : " + username);
            result.put("username", username);
            resultList.add(result);
        }

        return resultList;
    }

    //用户对某一投票事项进行投票
    @Override
    public List<Object> vote(JSONObject user) throws Exception {
        String name = user.getString("username");
        String voteResult = user.getString("voteresult");
        String voteId = user.getString("voteid");
        System.out.println(user);
        User user1 = userMapper.findId(name);
        String loginId = String.valueOf(user1.getId());

        List<Object> resultList = new ArrayList<>();
        JSONObject result = new JSONObject();

        int vote = Integer.parseInt(voteResult);

        //从智能合约上读取Y
        ECPoint Y = contract.getY(voteId);
        System.out.println("联合公钥为" + Y);

        //用Y加密投票
        ECPoint[] enVote = maskVote.encrypt(vote, ecgroup, h, Y);
        System.out.println("ecgroup" + ecgroup + "h = " + h);
        for (ECPoint ecPoint : enVote) {
            System.out.println("ecPoint = " + ecPoint);
        }
        List<String> enVoteList = new ArrayList<>();
        System.out.println("enVoteList.size() = " + enVoteList.size());
        //String[] enVoteList = new String[enVote.length];
        for (int i = 0; i < enVote.length; i++) {
            enVoteList.add(enVote[i].toString());
            System.out.println("enVote[i].toString() = " + enVote[i].toString());
        }
        for (String s : enVoteList) {
            System.out.println("enVoteList = " + s);
        }

        //将加密后的投票上传至智能合约
        TransactionReceipt transactionReceipt = contract.addSecVote(loginId, voteId, enVoteList);
        System.out.println(transactionReceipt);

        MaskVoteContract client = contract.Client();
        Tuple3<String, String, List<String>> addSecVoteInput = client.getAddSecVoteInput(transactionReceipt);
        if (addSecVoteInput != null) {
            result.put("result", "投票成功");
            result.put("code", "200");
        } else {
            result.put("result", "投票失败");
            result.put("code", "500");
        }

        //调用智能合约中的addVoteFlag方法，将结果设置为true
        contract.addVoteFlag(loginId, voteId);


        resultList.add(result);
        return resultList;

    }

    //预计票：
    //用户提交秘钥，用其秘钥加密g^R
    @Override
    public List<Object> preCount(JSONObject user) throws Exception {

        String name = user.getString("username");
        System.out.println("name = " + name);
        String key = user.getString("key");
        String voteId = user.getString("voteid");
        System.out.println(user);
        List<Object> resultList = new ArrayList<>();
        JSONObject result = new JSONObject();

        User user1 = userMapper.findId(name);
        System.out.println("user1 = " + user1);
        Integer loginIdInt = user1.getId();
        String loginIdString = String.valueOf(loginIdInt);

        BigInteger[][] keyInt = new BigInteger[2][t + 1];
        String[] keyString = key.split(","); //string-> BigInteger
        for (int i = 0; i < (t + 1); i++) {
            keyInt[0][i] = new BigInteger(keyString[i]);
            keyInt[1][i] = new BigInteger(keyString[i + t]);
        }


        //从智能合约中读取相乘后的加密选票
        ECPoint E1 = contract.getE1(voteId);
        System.out.println("加密后的选票E1 = " + E1);

        ECPoint enGR = maskVote.en_g_R(ecgroup, E1, keyInt[0][0]);
        System.out.println("加密结果enGR = " + enGR);
        System.out.println("ecgroup = " + ecgroup);
        List<String> GR = new ArrayList<>();
        GR.add(enGR.toString());

        //调用智能合约中的addPrecountFlag方法，将结果设置为true
        contract.addPrecount(loginIdString, voteId);

        //将加密结果enGR上传至智能合约
        TransactionReceipt transactionReceipt = contract.addg_R(loginIdString, voteId, GR);
        MaskVoteContract client = contract.Client();
        Tuple3<String, String, List<String>> addg_rInput = client.getAddg_RInput(transactionReceipt);
        if (addg_rInput != null) {
            result.put("result", "预计票成功");
            result.put("code", "200");
        } else {
            result.put("result", "预计票失败");
            result.put("code", "500");
        }

        resultList.add(result);
        return resultList;
    }

    //获取投票总票数
    @Override
    public List<Object> getSum(JSONObject user) throws Exception {

        String id = user.getString("voteid");
        System.out.println("前端获取的：" + id);
        Connection connection = contract.connection();
        String sql = "select * from event";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Object> resultList = new ArrayList<>();
        JSONObject result = new JSONObject();
        /*Date date = new Date();
        String format = sdf.format(date); //获取现在时间
        Date currentTime = sdf.parse(format);*/
        while (resultSet.next()) {

            String voteId = resultSet.getString("voteId");
            String voteItem = resultSet.getString("voteItem");
            if (id.equals(voteId)) {

                String voters = resultSet.getString("voterList");
                String voterList = voters.substring(1, voters.length() - 1);
                System.out.println("substring = " + voterList);
                String[] strings = voterList.split(", ");  //获取所有参与者
                ECPoint E0 = contract.getE0(voteId);

                ECPoint[] en_g_R_list = new ECPoint[strings.length];
                System.out.println("strings.length = " + strings.length);
                for (int i = 0; i < strings.length; i++) {
                    User user1 = userMapper.findId(strings[i]);
                    String id1 = String.valueOf(user1.getId());
                    ECPoint GRi = contract.getg_R(id1, voteId);

                    en_g_R_list[i] = GRi;
                }
                for (ECPoint ecPoint : en_g_R_list) {
                    System.out.println("ecPoint = " + ecPoint);
                }

                //计算总票数并存放进数据库
                int sum = maskVote.sum(ecgroup, en_g_R_list, h, E0);
                System.out.println("ecgroup = " + ecgroup);
                System.out.println("h = " + h);
                System.out.println("sum = " + sum);
                Integer sumResult = userMapper.updateSum(sum, voteItem);
                if (sumResult != 0){
                    result.put("result",sum);
                    result.put("code","200");
                    result.put("voterList",strings.length);
                }else {
                    result.put("result","null");
                    result.put("code","500");
                    result.put("voterList",strings.length);
                }

                resultList.add(result);
            }

        }

        return resultList;
    }

    @Override
    public String hello() {
        return "hello";
    }

    @Override
    public Integer findId(String name) {
        User userTemp = userMapper.findId(name);
        return userTemp.getId();
    }

    @Override
    public List<Object> addY(JSONObject user) throws Exception {

        String voteId = user.getString("voteid");

        Connection connection = contract.connection();
        String sql = "select * from event";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        JSONObject result = new JSONObject();   //创建返回给前端状态
        List<Object> resultList = new ArrayList<>();    //生成结果状态列表

        while (resultSet.next()){

            String sqlId = resultSet.getString("voteId");
            if (sqlId.equals(voteId)){
                String voters = resultSet.getString("voterList");
                String voterList = voters.substring(1, voters.length() - 1);
                System.out.println("substring = " + voterList);
                String[] strings = voterList.split(", ");  //获取所有参与者
                int[] idList = new int[strings.length];

                ECPoint[] A0List = new ECPoint[strings.length];   //从智能合约里读取的第i个参与者的A值数组的第一个值
                for (int t = 0; t < strings.length; t++) {
                    User voter = userMapper.findId(strings[t]);//获取每个参与者id
                    Integer voterIdInt = voter.getId();
                    String voterIdString = String.valueOf(voterIdInt);

                    idList[t] = voterIdInt;
                    ECPoint ecPoint = contract.getA(voterIdString);
                    A0List[t] = ecPoint;

                }
                System.out.println("ecgroup1 = " + ecgroup);
                ECPoint Y = maskVote.Y(A0List, ecgroup);
                System.out.println("ecgroup2 = " + ecgroup);
                List<String> YList = new ArrayList<>();
                YList.add(Y.toString());
                for (String s : YList) {
                    System.out.println("YList = " + s);
                }


                //将YList上传至智能合约 联合公钥
                TransactionReceipt transactionReceipt = contract.addY(voteId, YList);
                MaskVoteContract client = contract.Client();
                Tuple2<String, List<String>> addYInput = client.getAddYInput(transactionReceipt);
                if (addYInput != null){
                    result.put("result","添加成功");
                    result.put("code","200");
                }else {
                    result.put("result","添加失败");
                    result.put("code","400");
                }
                resultList.add(result);
                System.out.println(transactionReceipt);

            }
        }

        return resultList;

    }

    @Override
    public List<Object> addE(JSONObject user) throws Exception {

        String voteId = user.getString("voteid");

        Connection connection = contract.connection();
        String sql = "select * from event";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        JSONObject result = new JSONObject();   //创建返回给前端状态
        List<Object> resultList = new ArrayList<>();    //生成结果状态列表

        while (resultSet.next()){
            String sqlId = resultSet.getString("voteId");
            if (sqlId.equals(voteId)){
                String voters = resultSet.getString("voterlist");
                String voterList = voters.substring(1, voters.length() - 1);
                System.out.println("substring = " + voterList);
                String[] strings = voterList.split(", ");  //获取所有参与者
                for (String voter : strings) {
                    System.out.println("参与者为 = " + voter);
                }


                //调用密码算法的mul_en_vote()接口
                int[] idList = new int[strings.length];
                ECPoint[][] en_vote_list = new ECPoint[strings.length][2];
                for (int i = 0; i < strings.length; i++) {
                    User voter = userMapper.findId(strings[i]);//获取每个参与者id
                    Integer voterIdInt = voter.getId();
                    String voterIdString = String.valueOf(voterIdInt);
                    idList[i] = voterIdInt;
                    List SecVote = contract.getSecVote(voterIdString, voteId);

                    for (int j = 0; j < SecVote.size(); j++) {

                        System.out.println("SecVote.get(j) = " + SecVote.get(j).toString());
                        String SecVoteString = SecVote.get(j).toString();
                        String[] str = SecVoteString.split(",");
                        BigInteger o1 = new BigInteger(str[0], 16);
                        BigInteger o2 = new BigInteger(str[1], 16);
                        ECPoint ecPoint = new ECPoint(o1, o2);
                        System.out.println("ecPoint = " + ecPoint);
                        en_vote_list[i][j % 2] = ecPoint;
                    }

                    System.out.println("en_vote_list[0][0] = " + en_vote_list[0][0]);
                    System.out.println("en_vote_list[0][1] = " + en_vote_list[0][1]);
                    System.out.println("en_vote_list[1][0] = " + en_vote_list[1][0]);
                    System.out.println("en_vote_list[1][1] = " + en_vote_list[1][1]);
                    System.out.println("en_vote_list[1][1] = " + en_vote_list[2][0]);
                    System.out.println("en_vote_list[1][1] = " + en_vote_list[2][1]);

                }

                ECPoint[] mixedVoteList = maskVote.mul_en_vote(en_vote_list, ecgroup);
                System.out.println("ecgroup = " + ecgroup);
                for (ECPoint ecPoint : mixedVoteList) {
                    System.out.println("ecPoint = " + ecPoint);
                }
                List<String> mixedVote = new ArrayList<>();

                for (int i = 0; i < mixedVoteList.length; i++) {
                    mixedVote.add(mixedVoteList[i].toString());
                }
                for (String s : mixedVote) {
                    System.out.println("mixedVote = " + s);
                }

                //将相乘结果E存进智能合约
                TransactionReceipt transactionReceipt = contract.addMixedVote(voteId, mixedVote);
                MaskVoteContract client = contract.Client();
                Tuple2<String, List<String>> addMixedVoteInput = client.getAddMixedVoteInput(transactionReceipt);
                if (addMixedVoteInput != null){
                    result.put("result","添加成功");
                    result.put("code","200");
                }else {
                    result.put("result","添加失败");
                    result.put("code","400");
                }
                resultList.add(result);

            }
        }

        return resultList;
    }

    @Override
    public List<Object> Sum(JSONObject user) throws Exception {
        String voteItem = user.getString("voteitem");
        String voterList = user.getString("voterlist");
        String[] strings = voterList.split(", ");  //获取所有参与者

        String voteId = userMapper.findSqlId(voteItem);  //获取投票事项id

        ECPoint E0 = contract.getE0(voteId);

        ECPoint[] en_g_R_list = new ECPoint[strings.length];
        System.out.println("strings.length = " + strings.length);
        for (int i = 0; i < strings.length; i++) {
            User user1 = userMapper.findId(strings[i]);
            String id1 = String.valueOf(user1.getId());
            ECPoint GRi = contract.getg_R(id1, voteId);

            en_g_R_list[i] = GRi;
        }
        for (ECPoint ecPoint : en_g_R_list) {
            System.out.println("ecPoint = " + ecPoint);
        }

        JSONObject result = new JSONObject();   //创建返回给前端状态
        List<Object> resultList = new ArrayList<>();    //生成结果状态列表

        //计算总票数并存放进数据库
        int sum = maskVote.sum(ecgroup, en_g_R_list, h, E0);
        System.out.println("ecgroup = " + ecgroup);
        System.out.println("sum = " + sum);
        Integer sumResult = userMapper.updateSum(sum, voteItem);
        if (sumResult != 0){
            result.put("result","投票成功，请查看投票结果");
            result.put("code","200");
        }else {
            result.put("result","投票失败");
            result.put("code","500");
        }

        resultList.add(result);
        return resultList;
    }


}
